var cartApp = angular.module ("cartApp", []);

cartApp.controller("cartCtrl", function($scope, $http){

    $scope.refreshCart = function(){
       $http.get('/rest/cart/' + $scope.cartId).success(function (data){
           $scope.cart = data;
       });
    };

    $scope.clearCart = function(){
    	
        $http.get('/rest/cart/removecartitem/' + $scope.cartId).success(
        		
        		$scope.refreshCart()
        		
        
        );
    };

    $scope.initCartId = function(cartId){
        $scope.cartId = cartId;
        $scope.refreshCart(cartId);
    };

    $scope.addToCart = function(productId){
        $http.get('/rest/cart/add/' + productId).success(function (){
            alert('Product successfully added to the cart!');
        });
    };

    $scope.removeFromCart = function(productId){
    	
    	var pid=productId.item.product.id;
    	
        $http.get('/rest/cart/remove/' + pid).success(function(data){
           $scope.refreshCart();
           
        });
        
        return false;
    };

    $scope.calGrandTotal = function(){
        var grandTotal = 0;
       if($scope.cart){
        for (var i = 0; i < $scope.cart.cartItems.length; i++){
            grandTotal += $scope.cart.cartItems[i].totalPrice;
        }
       }
        return grandTotal;
    }
});